//待补充
$NG.AllReady(function (editPage, { useAction, useValuesChange, useUpdateRow, useBeforeClick, useDataIndexChange, useUpdateRows, useClick }) {
    const mstform = $NG.getCmpApi("p_form_dev_cost_budget_chg");
    const dgrid1 = $NG.getCmpApi("p_form_dev_labor_budget_chg"); //研发人工
    const dgrid2 = $NG.getCmpApi("p_form_dev_daliy_budget_chg");

    ////////////////////////////////////////////////////////////--mstform--////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////--mstform--////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////--mstform--////////////////////////////////////////////////////////////
    function highlightCellsBasedOnInput() {
        const rows = document.querySelectorAll(".table-row"); // 获取所有行
        rows.forEach((row) => {
            // 遍历每一行
            // 找到当前行的 "u_qty_ori" 和 "u_per_day_amt_ori" 单元格
            const qtyOriCell = row.querySelector('.virtual-table-cell[data-key="u_qty_ori"]');
            const perDayAmtOriCell = row.querySelector('.virtual-table-cell[data-key="u_personnel_rate"]');

            if (qtyOriCell && perDayAmtOriCell) {
                const perDayAmtValue = parseFloat(perDayAmtOriCell.textContent.trim().replace(/,/g, ""));
                if (perDayAmtValue > 6000) {
                    // 修改 "u_qty_ori" 的背景色
                    qtyOriCell.style.color = "red";
                } else {
                    //   qtyOriCell.style.backgroundColor = '';  // 恢复默认背景色（可选）
                }
            }
        });
    }
    useDataIndexChange(({ args, instance }) => {
        var items = args[0];
        if (items.u_position) {
            $NG.execServer("getSimpleDataByPhid", { phid: items.u_position }, function (res) {
                if (res) {
                    const datas = JSON.parse(res.data)[0].extendObjects;
                    // 尝试将 c_descript 转换为数字
                    const personnelRate = Number(datas.c_descript);
                    if (isNaN(personnelRate)) {
                        // 如果转换失败，可以设置一个默认值或者处理错误
                        console.error("Invalid value for u_personnel_rate:", datas.c_descript);
                    }
                    items.u_personnel_rate = personnelRate;
                    caculatedgrid();
                }
                dgrid1.refreshView();
            });
        }
        instance.updateRow(items);
    }, "p_form_dev_labor_budget_chg.u_position");
    useBeforeClick(({ args }) => {
        const isLock = (data) => {
            return data.reduce((value, item) => {
                if (item.checked && item.u_source_phid) {
                    value = false;
                }
                return value;
            }, true);
        };
        console.log(`删除行参数`, args);
        let lock = true;
        switch (args[0].containerId) {
            case "p_form_dev_labor_budget_chg":
                const arr1 = dgrid1.getData();
                lock = isLock(arr1);
                break;
            case "p_form_dev_daliy_budget_chg":
                const arr2 = dgrid2.getData();
                lock = isLock(arr2);
                break;
        }
        if (!lock) {
            $NG.alert("不能删除已存在关联记录的数据，只能删除当前表单新增数据！");
        }
        return lock;
    }, "deleterow");
    function hiddenInput(table, tabled) {
        //来源主键 || 主键
        $NG.updateUI((updater) => {
            updater.fieldSetForm[table].u_source_phid.setProps({
                hidden: true,
            });
            tabled.forEach((item) => {
                updater.editGrid[item].u_phid.setProps({
                    hidden: true,
                });
                updater.editGrid[item].u_source_phid.setProps({
                    hidden: true,
                });
            });
        });
    }

    hiddenInput("p_form_dev_cost_budget_chg", ["p_form_dev_labor_budget_chg", "p_form_dev_daliy_budget_chg"]);
    // 设置默认值人民币和汇率
    if (editPage.oType == "add") {
        $NG.updateState((updater) => {
            updater.data.p_form_dev_cost_budget_chg.setProps({
                phid_fcur: {
                    label: "人民币",
                    value: 1,
                },
                exchangerate: 1,
            });
        });
    }
    if (mstform) {
        cntMFilter();
        getPtInfoByPhid();
        getCntCount("p_form_dev_cost_budget_chg", "u_cnt", () => {
            getCntInfo();
            getErkaiInfo();
            getRg();
        });
        useValuesChange(({ args }) => {
            console.log(`监听项目选择变化`, args);
            getPtInfoByPhid();
            cntMFilter();
            getCntCount("p_form_dev_cost_budget_chg", "u_cnt", () => {
                getCntInfo();
                getErkaiInfo();
                getRg();
            });

            dgrid1.clearRows();
            dgrid2.clearRows();
        }, "p_form_dev_cost_budget_chg.phid_pc");
        useValuesChange(({ args }) => {
            console.log("合同监听", args[0]);
            getCntInfo();
            getErkaiInfo();
            dgrid1.clearRows();
            dgrid2.clearRows();
            getRg();
        }, "p_form_dev_cost_budget_chg.u_cnt");
        // 监听合同变化
        useValuesChange(({ args }) => {
            getCntInfo();
            getErkaiInfo();
        }, "p_form_dev_cost_budget_chg.u_cnt");
        if (editPage.oType == "add") {
            mstform.getItem("bill_name").setValue((mstform.getItem("phid_pc").getText() || "") + "二开费用预算变更单");
        }
    }
    useValuesChange(({ args }) => {
        mstform.getItem("bill_name").setValue((mstform.getItem("phid_pc").getText() || "") + "二开费用预算变更单");
        getYfFormTotalByPhidPc();
        getSbqdHeadInfoByPhidPc();
    }, "p_form_dev_cost_budget_chg.phid_pc");
    let lockTime = 0;
    let saveLock = true;
    if (editPage.oType == "add" || editPage.oType == "edit") {
        lockTime = setInterval(() => {
            const mstform = $NG.getCmpApi("p_form_dev_cost_budget_chg");
            if (mstform.getItem("u_source_phid").getValue()) {
                $NG.execServer("getSleftIsImport", { source: mstform.getItem("u_source_phid").getValue() }, (res) => {
                    console.log(`引用结果`, res);
                    if (res.count == 0) return;
                    const _data = JSON.parse(res.data)[0].extendObjects;
                    if (_data.app_status == "1") {
                        return;
                    }
                    saveLock = false;
                    $NG.alert("当前项目的设备清单未审核，不允许变更！！！");
                });
                clearInterval(lockTime);
            }
        }, 1000);
    }
    useBeforeClick(({ args }) => {
        if (!saveLock) {
            $NG.alert("当前项目的设备清单未审核，不允许变更！！！");
            return false;
        }
        return true;
    }, "save");
    useBeforeClick(({ args }) => {
        if (!saveLock) {
            $NG.alert("当前项目的设备清单未审核，不允许变更！！！");
            return false;
        }
        return true;
    }, "check");
    ////////////////////////////////////////////////////////////--dgrid1--////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////--dgrid1--////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////--dgrid1--////////////////////////////////////////////////////////////

    if (dgrid1) {
        var dgrid1_toolbar = $NG.getCmpApi("toolbar_p_form_dev_labor_budget_chg");
        dgrid1_toolbar.hideButton("attachment");
        useUpdateRows(({ args }) => {
            caculatedgrid();
            var sumAmtOri = 0;
            const rows = args[0];
            rows.forEach((items) => {
                if (items.u_sxfs == 1) {
                    sumAmtOri += parseFloat(items.u_labor_amt);
                }
                if (!items.u_year) {
                    items.u_year = new Date().getFullYear();
                    items.u_year_EXName = new Date().getFullYear();
                }
            });
            //汇总赋值
            $NG.updateState((updater) => {
                updater.data.p_form_dev_cost_budget_chg.setProps({
                    u_zk: sumAmtOri,
                });
            });
            dgrid1.refreshView();
            $NG.updateUI((updater) => {
                const fields = ["u_qty_ori", "u_per_day_amt_ori", "u_labor_amt_ori"];
                fields.forEach((field) => {
                    updater.editGrid.p_form_dev_labor_budget_chg[field].setProps({
                        // hidden: true, //隐藏
                        // required: true, //必输
                        disabled: true, //只读
                    });
                });
            });
            // highlightCellsBasedOnInput();
            generate15DigitNumber(args[0]);
            reduceNum();
            dgrid1.refreshView();
        }, "p_form_dev_labor_budget_chg");
        $NG.updateUI((updater) => {
            const fields = ["u_source_phid"];
            fields.forEach((field) => {
                updater.editGrid.p_form_dev_labor_budget_chg[field].setProps({
                    hidden: true, //隐藏
                });
            });
        });
    } else {
        console.log("dgrid2 获取失败");
    }

    ////////////////////////////////////////////////////////////--dgrid1 function--////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////--dgrid1 function--////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////--dgrid1 function--////////////////////////////////////////////////////////////

    function caculatedgrid() {
        console.log(`监听生效`);
        let u_total_dgrid1 = 0;
        let u_total_dgrid2 = 0;
        let u_total_dgrid = 0; //合计总费用

        dgrid1.getRows().forEach((items, rowIndex) => {
            // 人工费合计=人员费率*数量*人月
            items.u_labor_amt_vat = (Number(items.u_personnel_rate) || 0) * (Number(items.u_qty) || 0) * (Number(items.u_per_day_amt) || 0); //含税金额
            items.u_labor_amt = ((Number(items.u_personnel_rate) || 0) * (Number(items.u_qty) || 0) * (Number(items.u_per_day_amt) || 0)) / (1 + Number(items.u_tax_rate || 0)); //未税金额
            u_total_dgrid1 += parseFloat(items.u_labor_amt) || 0;
            dgrid1.refreshView();
        });
        dgrid2.getRows().forEach((items) => {
            let total = 0;
            for (let i = 1; i <= 12; i++) {
                const str = "u_expenses_" + String(i).padStart(2, "0");
                total += Number(items[str]) || 0;
            }
            items.u_dev_daliy_amt = total;
            u_total_dgrid2 += parseFloat(items.u_dev_daliy_amt);
            dgrid2.refreshView();
        });

        u_total_dgrid = u_total_dgrid1 + u_total_dgrid2;
        console.log(u_total_dgrid1, u_total_dgrid2, u_total_dgrid);
        let u_gross_profit_rate = (Number(window._catch_sbqd_amt.cnt_amt) || 0) && ((Number(window._catch_sbqd_amt.cnt_amt) || 0) - ((Number(window._catch_sbqd_amt.project_amt) || 0) + (Number(u_total_dgrid) || 0))) / (Number(window._catch_sbqd_amt.cnt_amt) || 0);

        $NG.updateState((updater) => {
            updater.data.p_form_dev_cost_budget_chg.setProps({
                u_total_labor_amt: u_total_dgrid1,
                u_total_daily_amt: u_total_dgrid2,
                u_total_dev_amt: u_total_dgrid,
                u_gross_profit_rate: u_gross_profit_rate,
            });
        });
    }

    ////////////////////////////////////////////////////////////--dgrid2--////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////--dgrid2--////////////////////////////////////////////////////////////
    ////////////////////////////////////////////////////////////--dgrid2--////////////////////////////////////////////////////////////

    if (dgrid2) {
        var dgrid2_toolbar = $NG.getCmpApi("toolbar_p_form_dev_daliy_budget_chg");
        dgrid2_toolbar.hideButton("attachment");
        useUpdateRows(({ args }) => {
            generate15DigitNumber(args[0]);
            caculatedgrid();
            reduceNum();
            dgrid2.refreshView();
        }, "p_form_dev_daliy_budget_chg");
        $NG.updateUI((updater) => {
            const fields = ["u_source_phid"];
            fields.forEach((field) => {
                updater.editGrid.p_form_dev_daliy_budget_chg[field].setProps({
                    hidden: true, //隐藏
                });
            });
        });
    } else {
        console.log("dgrid2 获取失败");
    }

    //////////////////////////////////////////////////////////// --function-- ////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////// --function-- ////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////// --function-- ////////////////////////////////////////////////////////////
    //表体差额计算
    function reduceNum() {
        setTimeout(() => {
            const yzrg = mstform.getItem("u_total_labor_amt").getValue() - mstform.getItem("u_total_labor_amt_ori").getValue();
            const tcfy = mstform.getItem("u_total_daily_amt").getValue() - mstform.getItem("u_total_daily_amt_ori").getValue();
            const yftotal = mstform.getItem("u_total_dev_amt").getValue() - mstform.getItem("u_total_dev_amt_ori").getValue();
            const zk = mstform.getItem("u_zk").getValue() - mstform.getItem("u_ori_zk").getValue();
            const rate = mstform.getItem("u_gross_profit_rate").getValue() - mstform.getItem("u_gross_profit_rate_ori").getValue();
            console.log(yzrg, tcfy, yftotal, zk);
            $NG.updateState((updater) => {
                updater.data.p_form_dev_cost_budget_chg.setProps({
                    u_total_labor_amt_gap: yzrg,
                    u_total_daily_amt_gap: tcfy,
                    u_total_dev_amt_gap: yftotal,
                    u_zk_gap: zk,
                    u_gross_profit_rate_chg: rate,

                    u_dev_amt_gap_sum: (Number(window._catch_yf_total_amt.total_amt) || 0) + yftotal,
                    u_labor_amt_gap_sum: (Number(window._catch_yf_total_amt.yfrg_total_amt) || 0) + yzrg,
                    u_daily_amt_gap_sum: (Number(window._catch_yf_total_amt.rc_total_amt) || 0) + tcfy,
                    u_zk_gap_sum: (Number(window._catch_yf_total_amt.rgzk_total_amt) || 0) + zk,
                });
            });
        }, 200);
    }

    //生成phid
    function generate15DigitNumber(arr) {
        console.log("编辑phid");
        arr.forEach((item) => {
            let str = "";
            // 获取当前时间戳
            let timestamp = Date.now().toString();
            // 如果时间戳不足 15 位，计算需要补充的位数
            let remainingLength = 15 - timestamp.length;
            if (remainingLength > 0) {
                // 生成指定长度的随机数
                let randomPart = "";
                for (let i = 0; i < remainingLength; i++) {
                    randomPart += Math.floor(Math.random() * 10);
                }
                // 将时间戳和随机数拼接成 15 位数字
                str = String(timestamp + randomPart);
            } else {
                // 如果时间戳长度超过 15 位，截取前 15 位
                str = String(timestamp.slice(0, 15));
            }
            console.log(str);
            if (!item.u_phid) {
                item.u_phid = str;
                dgrid1.refreshView();
                dgrid2.refreshView();
            }
        });
    }
    function getRg() {
        if (editPage.oType != "add") return;
        setTimeout(() => {
            // 赋值
            function _sum(num) {
                $NG.updateState((updater) => {
                    updater.data.p_form_dev_cost_budget_chg.setProps({
                        //   u_total_dev_amt_ori: num,
                    });
                });
            }
            // 临时存储上一次的费用
            const _countMaps = {
                _d1: 0,
                _d2: 0,
                _d3: 0,
                set d1(value) {
                    this._d1 = value;
                    _sum(this._d1 + this._d2 + this._d3);
                },
                set d2(value) {
                    this._d2 = value;
                    _sum(this._d1 + this._d2 + this._d3);
                },
                set d3(value) {
                    this._d3 = value;
                    _sum(this._d1 + this._d2 + this._d3);
                },
            };
            Object.defineProperties(_countMaps, {
                _d1: {
                    configurable: false,
                    writable: true,
                    enumerable: false,
                    value: 0,
                },
                _d2: {
                    configurable: false,
                    writable: true,
                    enumerable: false,
                    value: 0,
                },
                _d3: {
                    configurable: false,
                    writable: true,
                    enumerable: false,
                    value: 0,
                },
            });
            if (dgrid1) {
                $NG.execServer("getDevLaborBudgetInfo", { phid_pc: mstform.getItem("phid_pc").getValue() }, function (res) {
                    let _data = null;
                    if (typeof res.data === "string") {
                        _data = JSON.parse(res.data);
                    } else {
                        _data = res.data;
                    }
                    console.log(`人工明细`, _data, res);
                    //默认增行,批量新增表体数据
                    var gridArr = []; //定义表体数组
                    var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
                    for (var i = 0; i < gridCount; i++) {
                        const phid = _data[i].extendObjects.mphid;
                        var gridObj = {};
                        if (!mstform.getItem("u_source_phid").getValue()) {
                            $NG.updateState((updater) => {
                                updater.data.p_form_dev_cost_budget_chg.setProps({
                                    u_source_phid: phid,
                                });
                            });
                        }
                        console.log(_data[i].extendObjects, 11111111111111);

                        //对表体字段进行赋值,可以取数据库中的值进行赋值
                        // 来源主键
                        gridObj.u_source_phid = _data[i].extendObjects.phid;
                        // 年度
                        gridObj.u_year = _data[i].extendObjects.u_year;
                        // // 人员岗位
                        gridObj.u_position_EXName = _data[i].extendObjects.position_name;
                        gridObj.u_position = _data[i].extendObjects.position_phid;
                        // // 人员费率
                        gridObj.u_personnel_rate = _data[i].extendObjects.u_personnel_rate;
                        // // 人工费合计
                        gridObj.u_labor_amt_ori_vat = _data[i].extendObjects.u_labor_amt_vat;
                        gridObj.u_labor_amt_vat = _data[i].extendObjects.u_labor_amt_vat;
                        gridObj.u_labor_amt_ori = _data[i].extendObjects.u_labor_amt;
                        gridObj.u_labor_amt = _data[i].extendObjects.u_labor_amt;
                        // // 数量
                        gridObj.u_qty = _data[i].extendObjects.u_qty;
                        gridObj.u_qty_ori = _data[i].extendObjects.u_qty;
                        // 税率
                        gridObj.u_tax_rate_ori = _data[i].extendObjects.u_tax_rate;
                        gridObj.u_tax_rate = _data[i].extendObjects.u_tax_rate;
                        // // 1- 12 月
                        // for (let j = 1; j <= 12; j++) {
                        // 	const _str = `u_man_days_${j < 10 ? '0' + j : j}`
                        // 	const _str_ori = `u_man_days_${j < 10 ? '0' + j : j}_ori`
                        // 	gridObj[_str] = _data[i].extendObjects[_str];
                        // 	gridObj[_str_ori] = _data[i].extendObjects[_str];
                        // }
                        gridObj.u_prc = _data[i].extendObjects.u_prc;
                        gridObj.u_gn = _data[i].extendObjects.u_gn;
                        gridObj.u_sxfs = _data[i].extendObjects.u_sxfs;
                        gridObj.u_per_day_amt_ori = _data[i].extendObjects.u_per_amt_day;
                        gridObj.u_per_day_amt = _data[i].extendObjects.u_per_amt_day;
                        gridObj.u_price_amt = _data[i].extendObjects.u_price_amt;
                        gridArr.push(gridObj);
                    }
                    //调用新增表体行数据的函数
                    let _count = 0;
                    gridArr.forEach((item) => {
                        _count += item.u_labor_amt_ori;
                    });
                    $NG.updateState((updater) => {
                        _countMaps.d1 = _count;
                        updater.data.p_form_dev_cost_budget_chg.setProps({
                            // u_total_labor_amt_ori: _count,
                        });
                    });
                    dgrid1.addRows(gridArr);
                });
            }
            if (dgrid2) {
                //日常
                $NG.execServer(
                    "getDevDaliyBudgetInfo",
                    {
                        phid_pc: mstform.getItem("phid_pc").getValue(),
                    },
                    function (res) {
                        let _data = null;
                        if (typeof res.data === "string") {
                            _data = JSON.parse(res.data);
                        } else {
                            _data = res.data;
                        }
                        console.log(`测试测试日常`, _data);
                        //默认增行,批量新增表体数据
                        var gridArr = []; //定义表体数组
                        var gridCount = res.count; //增加的行数,可根据从数据库从取出的数据总数增行
                        for (var i = 0; i < gridCount; i++) {
                            //对表体字段进行赋值,可以取数据库中的值进行赋值
                            var gridObj = {};
                            gridObj.u_source_phid = _data[i].extendObjects.phid;
                            gridObj.u_year = _data[i].extendObjects.u_year;
                            gridObj.u_dev_daliy_amt = _data[i].extendObjects.u_dev_daliy_amt;
                            gridObj.u_dev_daliy_amt_ori = _data[i].extendObjects.u_dev_daliy_amt;
                            gridObj.u_expense_code = _data[i].extendObjects.u_expense_code;
                            gridObj.u_expense_code_EXName = _data[i].extendObjects.u_expense_name;
                            gridObj.u_expense_description = _data[i].extendObjects.u_expense_description;
                            // 1- 12 月
                            for (let j = 1; j <= 12; j++) {
                                const _str = `u_expenses_${j < 10 ? "0" + j : j}`;
                                const _str_ori = `u_expenses_${j < 10 ? "0" + j : j}_ori`;
                                gridObj[_str] = _data[i].extendObjects[_str];
                                gridObj[_str_ori] = _data[i].extendObjects[_str];
                            }
                            gridArr.push(gridObj);
                        }
                        let _count = 0;
                        gridArr.forEach((item) => {
                            _count += item.u_annual_svc_amt;
                        });
                        $NG.updateState((updater) => {
                            _countMaps.d2 = _count;
                            updater.data.p_form_dev_cost_budget_chg.setProps({
                                //   u_total_daily_amt_ori: _count,
                            });
                        });
                        //调用新增表体行数据的函数
                        dgrid2.addRows(gridArr);
                        dgrid2.refreshView();
                    }
                );
            }
        }, 200);
    }

    // 获取项目信息
    function getPtInfoByPhid() {
        if (mstform.getItem("phid_pc").getValue()) {
            $NG.execServer("getPtInfoByPhid", { phid: mstform.getItem("phid_pc").getValue() }, function (res) {
                const datas = JSON.parse(res.data)[0].extendObjects;
                console.log(`获取项目信息`, datas);
                //帮助字段赋值
                $NG.updateState((updater) => {
                    updater.data.p_form_dev_cost_budget_chg.setProps({
                        u_pc_no: datas.pc_no, //项目编码
                        //项目类型
                        u_pc_type: {
                            label: datas.type_name,
                            value: datas.type_phid,
                        },
                        u_sqgw: {
                            //售前顾问
                            value: datas.user_sqgw_phid,
                            label: datas.user_sqgw_name,
                        },
                        //事业部
                        u_division: {
                            value: datas.division_phid,
                            label: datas.division_name,
                        },
                        u_regional_center: {
                            //区域中心
                            value: datas.regional_center_phid,
                            label: datas.regional_center_name,
                        },
                        u_dept: {
                            //部门
                            value: datas.dept_phid,
                            label: datas.dept_name,
                        },
                        phid_org: {
                            //部门
                            value: datas.org_phid,
                            label: datas.org_name,
                        },
                        u_region: {
                            //部门
                            value: datas.dept_phid,
                            label: datas.dept_name,
                        },
                        u_ywx: {
                            //产品线
                            value: datas.midwife_phid,
                            label: datas.midwife_name,
                        },
                        u_ywlx: {
                            //项目类型
                            value: datas.user_ywlx,
                            label: datas.ywlx_name,
                        },
                    });
                });
                // 判断是否是提前施工
                let lock = true;
                if (datas.user_sf_tqsg == '1') {
                    lock = false
                } else {
                    lock = true
                }
                console.log(`是否提前施工项目`, datas.user_sf_tqsg);
                $NG.updateUI((updater) => {
                    updater.fieldSetForm.p_form_dev_cost_budget_chg.u_cnt.setProps({
                        required: lock
                    })
                })
            });
        }
    }

    // 获取合同信息
    function getCntInfo() {
        $NG.execServer("getCntMInfoByPhid", { phid: mstform.getItem("u_cnt").getValue() }, function (res) {
            const datas = JSON.parse(res.data)[0].extendObjects;
            console.log(`合同：`, datas);
            //帮助字段赋值
            $NG.updateState((updater) => {
                updater.data.p_form_dev_cost_budget_chg.setProps({
                    u_agreed_sts_dt: datas.start_dt, //计划完工日期
                    u_agreed_pcl_dt: datas.end_dt, //计划竣工日期
                    u_cnt_no: datas.pcm_no,
                    u_cnt_amt_vat: datas.cnt_sum_vat_fc,
                    u_cnt_amt: datas.cnt_sum_fc,
                    u_invoice_type: {
                        label: datas.invoice_type_name,
                        value: datas.invoice_type_phid,
                    },
                });
            });
        });
    }

    function getErkaiInfo() {
        $NG.execServer("getErkai", { cnt: mstform.getItem("u_cnt").getValue() }, function (res) {
            const datas = JSON.parse(res.data)[0].extendObjects;
            console.log(mstform.getItem("u_cnt").getValue());

            console.log(`二开费用：`, datas);
            if (datas.app_status == 1) {
                //帮助字段赋值
                $NG.updateState((updater) => {
                    updater.data.p_form_dev_cost_budget_chg.setProps({
                        u_total_daily_amt_ori: datas.u_total_daily_amt,
                        u_total_labor_amt_ori: datas.u_total_labor_amt,
                        u_total_dev_amt_ori: datas.u_total_dev_amt,
                        u_ori_zk: datas.u_zk,
                    });
                });
            }
        });
    }

    // 过滤合同
    function cntMFilter() {
        if (!mstform.getItem("phid_pc").getValue()) {
            return;
        }
        console.log(`开始过滤`);
        $NG.updateUI((updater, state) => {
            updater.fieldSetForm.p_form_dev_cost_budget_chg.u_cnt.setProps({
                onBeforeOpen: async () => {
                    var phid_pc = $NG.getCmpApi("p_form_dev_cost_budget_chg").getItem("phid_pc").getValue();
                    if (!phid_pc) {
                        $NG.alert("请先选择项目");
                        return false;
                    } else {
                        return true;
                    }
                },
                ...(!!$NG.getCmpApi("p_form_dev_cost_budget_chg").getItem("phid_pc").getValue() && {
                    clientSqlFilter: {
                        bill_type: 1,
                        phid_pc: $NG.getCmpApi("p_form_dev_cost_budget_chg").getItem("phid_pc").getValue(),
                    },
                }),
            });
        });
    }

    // 汇总明细数据到主表
    function sum() {
        const _rowD = dgrid1.getRows();
        const _rowD2 = dgrid2.getRows();
        let _countD1 = 0;
        let _countD2 = 0;
        _rowD.forEach((item) => {
            _countD1 += Number(item.u_labor_amt) || 0;
        });
        _rowD2.forEach((item) => {
            _countD2 += Number(item.u_dev_daliy_amt) || 0;
        });
        $NG.updateState((updater) => {
            updater.data.p_form_dev_cost_budget_chg.setProps({
                u_total_labor_amt: _countD1,
                u_total_daily_amt: _countD2,
                u_total_dev_amt: _countD1 + _countD2,
            });
        });
    }

    // 获取二开费用表头的相关金额
    getYfFormTotalByPhidPc();
    function getYfFormTotalByPhidPc() {
        const phid_pc = mstform.getItem("phid_pc").getValue();
        console.log(`当前项目`, phid_pc);
        if (!phid_pc) return;
        $NG.execServer("getYfFormTotalByPhidPc", { phid_pc }, (res) => {
            if (res.count == 0) return;
            const _data = JSON.parse(res.data)[0].extendObjects;
            window._catch_yf_total_amt = { ..._data };
        });
    }

    getSbqdHeadInfoByPhidPc();
    function getSbqdHeadInfoByPhidPc() {
        window._catch_sbqd_amt = {};
        const phid_pc = mstform.getItem("phid_pc").getValue();
        if (!phid_pc) return;
        $NG.execServer("getSbqdHeadInfoByPhidPc", { phid_pc }, (res) => {
            if (res.count == 0) return;
            const _data = JSON.parse(res.data)[0].extendObjects;
            const map = {
                cnt_amt: _data.u_cnt_amt,
                project_amt: (Number(_data.u_total_cost_amt) || 0) - (Number(_data.u_sec_dev_amt) || 0),
                total_rate: _data.u_signed_gm_rate,
                outher: _data,
            };
            window._catch_sbqd_amt = { ...map };
            if (editPage.oType != "view") {
                $NG.updateState((updater) => {
                    updater.data.p_form_dev_cost_budget_chg.setProps({
                        u_gross_profit_rate_ori: _data.u_signed_gm_rate,
                    });
                });
            }
        });
    }
});

//获取合同数量
function getCntCount(table, key, fun) {
    if (!$NG.getCmpApi(table).getItem("phid_pc").getValue()) return;
    $NG.execServer("getCntCount", { type: 1, phid_pc: $NG.getCmpApi(table).getItem("phid_pc").getValue() }, (res) => {
        console.log(res, "count");
        switch (res.count) {
            case 0:
                return;
            case 1:
                const datas = JSON.parse(res.data)[0].extendObjects;
                const temp_map = {};
                temp_map[key] = datas.phid;
                temp_map[`${key}_EXName`] = datas.bill_name;
                $NG.updateState((updater) => {
                    updater.data[table].setProps({
                        ...temp_map,
                    });
                    setTimeout(() => {
                        if (fun) {
                            fun();
                        }
                    }, 200);
                });
        }
    });
}
